package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Description:
 * @ClassName: UserController
 * @Author: xmc
 * @Date: 2022/8/18 21:02
 * @Version: 1.0
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> send(@RequestBody User user, HttpSession httpSession){
        //获取手机号

        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)) {
            //生成随机的4为验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("随机生成的验证码为:{}",code);
            //调用阿里云提供的短信服务Api
            //SMSUtils.sendMessage("签名","模板code","手机号",code);
            //将验证码保存到Ssesion
            httpSession.setAttribute(phone,code);
            return R.success("手机验证码发送成功");
        }

       return R.error("手机验证码发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession httpSession){

      log.info("map封装:{}",map);
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从ssesion中获取code
        String codeForSession = (String) httpSession.getAttribute(phone);
        //ssesion中获取code获取的验证码比较
        if(codeForSession!= null && codeForSession.equals(code)){
            //对比成功，登录成功

            //判断手机号是否在user表中，没有自动注册
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user = userService.getOne(wrapper);
            if(user == null){
                //没有自动注册
                User user1 = new User();
                user1.setPhone(phone);
                userService.save(user1);
                httpSession.setAttribute("user",user1.getId());
                return R.success(user);
            }
            httpSession.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
    }
}
